//index.js
//获取app实例
const app = getApp();
var utils = require("../../utils/util.js");
var noLogin = require("../template/noLogin.js");
Page({
  data: {
    isTop: false, // 文字滚动的状态，false初始位置，true顶部位置
    isindicator: 0, //轮播图当前下标值
    baseURL: {
      // swipe: 'https://jrtest.0791jr.com/data/attachment/advert/',//轮播图片的基础url
      nav: 'https://try.0791jr.com/data/attachment/nav/', //导航图标的基础url
    },
    baseGoodsImgUrl: 'https://try.0791jr.com/data/attachment/item/',//猜你喜欢的基础url
    maxHeight: 0,   //这是swiper要动态设置的高度属性
    hasUserInfo: false,   //判断是否获取了用户数据  默认true为获取了
    phoneNumber:'12213232312'
  },
  //页面开始加载
  onLoad: function () {
    this.options.data = 1; 
    if (!wx.getStorageSync('userInfo')) {
      noLogin.showNoLogin(this).then(() => {
        //用户授权后更新用户数据
        this.init();
      }).catch(() => {
        // this.setData({ hasUserInfo: false })
        wx.reLaunch({
          url: '/pages/login/login',
        })
      });  //判断用户未登录，弹出授权窗口
    } else {
      // this.setData({ hasUserInfo: true }); //判断用户已登录，关闭授权窗口
      app.userLogin(() => {
        this.init();
      })
    }
  },

  move() { },

  //获取数据
  init(cb) {
    console.log(app.globalData.userId);
    //获取首页数据
    wx.showLoading({title: '加载中...'});
    wx.showNavigationBarLoading();
    wx.request({
      url: app.baseURL + 'Index&a=index&userId=' + app.globalData.userId,
      success: (res) => {
        if (res.statusCode == 200) {
          let data = res.data;
          console.log(res.data)
          data.outauto.forEach((item) => {   //循环轮播图片
            wx.getImageInfo({   //获取图片信息
              src: item.content,  //图片路径
              success: res => {
                this.setData({
                  maxHeight: res.height > this.data.maxHeight ? res.height : this.data.maxHeight    //获取图片中高最高的 
                })
              }
            })
          })
          let activity = data.act_list;
          if (activity.length > 6){
            activity.length = 6;
          }
          this.setData({ 
            data: data, hasUserInfo: true,
            phoneNum: data.tel.data,
            activity: data.act_list,  //活动模块导航
          });
          //执行文字滚动动画
          this.scroll();
          // 如果有回调函数执行回调
          typeof cb == 'function' && cb();
          wx.hideNavigationBarLoading();
          wx.hideLoading();
        }
      }
    });
  },

  //文字滚动
  scroll() {
    let list = this.data.data.article; //获取数据列表
    clearInterval(this.Interval);
    //3s滚动一次
    this.Interval = setInterval(() => {
      this.setData({
        isTop: true
      });
      //tanslation = 300ms，故数据变动的间隔也是300ms
      setTimeout(() => {
        let list = this.data.data.article
        list.push(list.shift());
        this.setData({
          'data.article': list,
          isTop: false
        });
      }, 300);
    }, 3000);
  },

  //活动导航跳转
  goActivity (e){
    let types = e.currentTarget.dataset.type;  //1积分商城 2优惠券 3特价促销 4限时秒杀 5分享有礼 6砍价
    switch (types){
      case "1":
        wx.navigateTo({
          url: '/pages/integral/pages/integral/integral',
        })
        break;
      case "2":
        wx.navigateTo({
          url: '/pages/coupon/coupon',
        })
        break;
      case "3":
        wx.navigateTo({
          url: '/pages/discount/discount',
        })
        break;
      case "4":
        wx.navigateTo({
          url: '/pages/seckill/seckill',
        })
        break;
      case "6":
        wx.navigateTo({
          url: '/pages/bargain/bargain',
        })
        break;
      default:
        console.log("没有此项活动");
    }
  },

  //点击 跳转详情页
  clickToDetail(e) {
    let item_id = e.currentTarget.dataset.item_id;
    if (item_id == null) return;
    wx.navigateTo({
      url: '../detail/detail?item_id=' + item_id
    });
  },

  // 导航跳转
  toNavUrl(e){
    const data = e.currentTarget.dataset;
    if (data.opentype == "switchTab"){
      wx.switchTab({
        url: '/pages/' + data.url + '/' + data.url,
      })
    }
    if (data.opentype == "navigateTo") {
      var navUrl = null;
      if (data.url == "integral"){
        navUrl = "/pages/integral/pages/" + data.url + '/' + data.url
      }else if (data.url == "integralTask") {
        navUrl = "/pages/integral/pages/" + data.url + '/' + data.url
      } else if (data.url == "bargain"){
        navUrl = "/pages/order/order?jk=index&type=0";
      }else{
        navUrl = '/pages/' + data.url + '/' + data.url
      }
      if (!wx.getStorageSync('userInfo')) {
        noLogin.showNoLogin(this).then(() => {
          //用户授权后更新用户数据
          wx.navigateTo({
            url: navUrl,
          })
        }).catch(() => {
          this.setData({ hasUserInfo: false })
        });  //判断用户未登录，弹出授权窗口
      } else {
        this.setData({ hasUserInfo: true }); //判断用户已登录，关闭授权窗口
        wx.navigateTo({ url: navUrl,})
      }
    }
  },

  //查看更多
  Seemore (e){
    const catedid = e.currentTarget.dataset.catedid;
    const catedname = e.currentTarget.dataset.name;
    app.globalData.catedid = catedid;
    app.globalData.catedname = catedname;
    app.globalData.catedType = 1;
    wx.switchTab({
      url: '/pages/classify/classify',
    })
  },

  //用户确认授权
  // WeChatUserInfo: function (e) {
  //   if (e.detail.userInfo) {
  //     this.setData({ hasUserInfo: true });//发起登录
  //     noLogin.getUserInfo(this).then(()=>{
  //       this.init();
  //     });//用户授权后更新用户数据
  //   } else {
  //     wx.showModal({
  //       title: '温馨提示',
  //       content: '拒绝微信授权将无法使用部分功能',
  //       success: res => {
  //         if (res.confirm) {
  //           this.init();
  //           this.setData({ hasUserInfo: true });
  //         }
  //       }
  //     })
  //   }
  // },

  //下拉刷新
  onPullDownRefresh() {
    this.init(wx.stopPullDownRefresh());
  },

  //监听页面隐藏
  onHide: function () {
    clearInterval(this.Interval);  //停止定时器
  },
  //改变轮播图指示点
  changeIndicator: function (e) {
    this.setData({
      isindicator: e.detail.current
    })
  },
  
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: app.globalData.title,
        path: '/pages/index/index?other_user_id=' + app.globalData.userId,
        imageUrl: 'https://try.0791jr.com/WeChat/images/integralTaskshare.png'
      }
    }
    
  },

  // 按号码响应函数
  phoneNumTap: function () {
    var that = this;
    // 提示呼叫号码还是将号码添加到手机通讯录
    wx.showActionSheet({
      itemList: ['呼叫', '添加联系人'],
      success: function (res) {
        if (res.tapIndex == 0) {
          // 呼叫号码
          wx.makePhoneCall({
            phoneNumber: that.data.phoneNum,
          })
        } else if (res.tapIndex == 1) {
          // 添加到手机通讯录
          wx.addPhoneContact({
            firstName: 'customer',//联系人姓名
            mobilePhoneNumber: that.data.phoneNum,//联系人手机号
          })
        }
      }
    })
  }
});

